package com.gaoding.shared.dict.controller;

import com.gaoding.shared.dict.dto.response.DictLanguageRespDTO;
import com.gaoding.shared.dict.dto.response.DictServiceLanguageRespDTO;
import com.gaoding.shared.dict.dto.response.DictServiceListResponseDTO;
import com.gaoding.shared.dict.dto.response.DictTextContentRespDTO;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;

import java.lang.reflect.ParameterizedType;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 基础控制器
 * 主要封装sql导出功能
 * @author mobai
 * @since 2021/4/20 10:14
 */
public abstract class BaseController<E> {

    protected Class<E> entityClass = (Class<E>) ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[0];

    protected Map<Class, String> SQL_MAP = new HashMap<Class, String>(4) {{
        put(DictServiceListResponseDTO.class, "delete from dict_service where service_code='%s'; \r\n insert into `dict_service`(service_code,service_name,status,created_at,updated_at) values('%s','%s',1,now(),now());\r\n");
        put(DictLanguageRespDTO.class, "delete from dict_language where language_code='%s'; \r\n insert into `dict_language`(language_code,language_name,status,created_at,updated_at) values('%s','%s',1,now(),now());\r\n");
        put(DictServiceLanguageRespDTO.class, "delete from dict_service_language where service_code='%s' and language_code='%s'; \r\n insert into `dict_service_language`(service_code,language_code,status,sort,version,created_at,updated_at) values('%s','%s',1,1,%s,now(),now());\r\n");
        put(DictTextContentRespDTO.class, "delete from dict_text_content where service_code='%s' and language_code='%s' and text_key='%s'; \r\n insert into dict_text_content(service_code, language_code, status, sort, version, text_type, text_key, text_content, created_at, updated_at) values('%s', '%s', 1, 1, 1, '%s', '%s','%s',now(),now());\r\n");
    }};


    @PostMapping("/sql/{id}")
    public String exportSql(@PathVariable("id") Long id, @RequestBody E e) {
        String[] args = args(e);
        String sql = SQL_MAP.get(entityClass);
        return String.format(sql, args);
    }

    @PostMapping("/sqls")

    public String batchExportSql(@RequestParam("ids") List<Long> ids, @RequestBody List<E> es) {
        StringBuilder result = new StringBuilder();
        result.append("/* \r\n");
        result.append(" generate by dict-admin \r\n");
        result.append(" */ \r\n");
        for (int i = 0, j = ids.size(); i < j; i++) {
            result.append(exportSql(ids.get(i), es.get(i)));
        }
        return result.toString();
    }

    protected abstract String[] args(E e);


}
